package com.smart.home.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;

/**
 * 字符串工具类
 */
public class StringUtils {

    public static String toHex(byte b) {
        String result = Integer.toHexString(b & 0xFF);
        if (result.length() == 1) {
            result = '0' + result;
        }
        return result;
    }

    /**
     * 16进制字符串转10进制
     *
     * @param hex 16进制字符串
     * @return 10进制数字
     */
    public static int hexToInt(String hex) {
        if (isEmpty(hex)) {
            throw new IllegalArgumentException("输入参数错误");
        }
        BigInteger bigInteger = new BigInteger(hex, 16);
        return bigInteger.intValue();
    }

    private static String hexString = "0123456789ABCDEF";

    public static String GBKToStringHex(String str) {
        // 根据默认编码获取字节数组
        byte[] bytes = str.getBytes();
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        // 将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
        }
        return sb.toString();
    }

    public static String Utf82GBKStringHex(String str) {
        StringBuffer sb = new StringBuffer();
        try {
            for (byte b : str.getBytes("gbk")) {
                sb.append(Integer.toHexString(b & 0xFF));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static String toHexString(int i) {
        String s = Integer.toHexString(i);
        if (s.length() < 2) {
            s = "0" + s;
        }
        return s;
    }

    /**
     * 是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(Object str) {
        return (str == null || "".equals(str));
    }

}
